﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Composition;

namespace CC98.ComponentModel
{
    [Export(typeof(InitializeProcessor))]
    public class InitializeProcessor
    {
        [ImportingConstructor]
        public InitializeProcessor(
            [ImportMany]
            IEnumerable<Lazy<IInitializeHandler, InitializeMetadata>> initHandlers
            )
        {
            this._initHandlers = initHandlers;
        }

        public async void StartAsync(ActionScope mode, Action<Task> continueTask = null)
        {
            await Task.Run(new Action(() =>
                {
                    var handlers = this._initHandlers.Where(p => p.Metadata.Scope == mode);

                    foreach (var handler in handlers)
                    {
                        this.OnProgressChanged(handler.Value.Name);
                        handler.Value.Initialize();
                    }
                })).ContinueWith(new Action<Task>((t)=>
                    {
                        if (continueTask != null)
                            continueTask(t);
                    }));
        }

        protected void OnProgressChanged(string name)
        {
            if (this.ProgressChanged != null)
                this.ProgressChanged(this, new InitializeProcessorProgressChangedEventArgs(name));
        }

        public event EventHandler<InitializeProcessorProgressChangedEventArgs> ProgressChanged;

        private IEnumerable<Lazy<IInitializeHandler, InitializeMetadata>> _initHandlers;
    }

    public class InitializeProcessorProgressChangedEventArgs : EventArgs
    {
        public InitializeProcessorProgressChangedEventArgs(string name)
        {
            this.Name = name;
        }

        public string Name { get; private set; }
    }
}
